package cn.skycity.gateway.oauth2;

import cn.hutool.json.JSONUtil;
import cn.skycity.framework.core.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginLoseHandler extends HttpBasicServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        Result<String> resultVO = Result.failed();
        ServerHttpResponse response = exchange.getResponse();
        return response.writeAndFlushWith(
                    Flux.just(ByteBufFlux.just(response.bufferFactory().wrap(JSONUtil.toJsonStr(resultVO).getBytes(
                            StandardCharsets.UTF_8)))));
    }
}
